package com.example.controller;

import com.example.model.QualityCheck;
import com.example.repository.QualityCheckRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wash/quality-checks")
@Tag(name = "质检管理", description = "质检记录的创建、查询、更新和管理")
public class QualityCheckController {
    
    @Autowired
    private QualityCheckRepository qualityCheckRepository;

    @PostMapping
    @Operation(summary = "创建质检记录")
    public ResponseEntity<QualityCheck> createQualityCheck(@Valid @RequestBody QualityCheck qualityCheck) {
        QualityCheck createdQualityCheck = qualityCheckRepository.save(qualityCheck);
        return ResponseEntity.ok(createdQualityCheck);
    }

    @GetMapping
    @Operation(summary = "获取质检记录列表")
    public ResponseEntity<Page<QualityCheck>> getAllQualityChecks(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "checkedAt") String sortBy,
            @RequestParam(defaultValue = "desc") String sortDir,
            @RequestParam(required = false) String result,
            @RequestParam(required = false) Boolean needsRework) {
        
        Sort sort = Sort.by(Sort.Direction.fromString(sortDir), sortBy);
        Pageable pageable = PageRequest.of(page, size, sort);
        
        return ResponseEntity.ok(qualityCheckRepository.findAll(pageable));
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取质检记录详情")
    public ResponseEntity<QualityCheck> getQualityCheckDetail(@PathVariable Long id) {
        return qualityCheckRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新质检记录")
    public ResponseEntity<QualityCheck> updateQualityCheck(
            @PathVariable Long id,
            @Valid @RequestBody QualityCheck qualityCheck) {
        return qualityCheckRepository.findById(id)
                .map(existingQualityCheck -> {
                    qualityCheck.setId(id);
                    QualityCheck updatedQualityCheck = qualityCheckRepository.save(qualityCheck);
                    return ResponseEntity.ok(updatedQualityCheck);
                })
                .orElse(ResponseEntity.notFound().build());
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除质检记录")
    public ResponseEntity<Void> deleteQualityCheck(@PathVariable Long id) {
        if (qualityCheckRepository.existsById(id)) {
            qualityCheckRepository.deleteById(id);
            return ResponseEntity.ok().build();
        }
        return ResponseEntity.notFound().build();
    }

    @GetMapping("/result/{result}")
    @Operation(summary = "根据质检结果获取记录")
    public ResponseEntity<List<QualityCheck>> getQualityChecksByResult(@PathVariable String result) {
        try {
            QualityCheck.QualityResult qualityResult = QualityCheck.QualityResult.valueOf(result.toUpperCase());
            List<QualityCheck> qualityChecks = qualityCheckRepository.findByResult(qualityResult);
            return ResponseEntity.ok(qualityChecks);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/rework")
    @Operation(summary = "获取需要返工的质检记录")
    public ResponseEntity<List<QualityCheck>> getReworkQualityChecks() {
        List<QualityCheck> reworkChecks = qualityCheckRepository.findByNeedsReworkTrue();
        return ResponseEntity.ok(reworkChecks);
    }

    @GetMapping("/today")
    @Operation(summary = "获取今日质检记录")
    public ResponseEntity<List<QualityCheck>> getTodayQualityChecks() {
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<QualityCheck> todayChecks = qualityCheckRepository.findTodayQualityChecks(startOfDay, endOfDay);
        return ResponseEntity.ok(todayChecks);
    }

    @GetMapping("/high-quality")
    @Operation(summary = "获取高质量订单")
    public ResponseEntity<List<QualityCheck>> getHighQualityOrders() {
        List<QualityCheck> highQualityOrders = qualityCheckRepository.findHighQualityOrders();
        return ResponseEntity.ok(highQualityOrders);
    }

    @GetMapping("/statistics")
    @Operation(summary = "获取质检统计")
    public ResponseEntity<Map<String, Object>> getQualityCheckStatistics() {
        Map<String, Object> statistics = new HashMap<>();
        
        // 各质检结果统计
        List<Object[]> resultStats = qualityCheckRepository.countByResult();
        statistics.put("resultStatistics", resultStats);
        
        // 质检员工作量统计
        List<Object[]> inspectorStats = qualityCheckRepository.countByInspector();
        statistics.put("inspectorStatistics", inspectorStats);
        
        // 总质检记录数
        long totalChecks = qualityCheckRepository.count();
        statistics.put("totalChecks", totalChecks);
        
        // 今日质检数
        LocalDateTime startOfDay = LocalDateTime.now().toLocalDate().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        List<QualityCheck> todayChecks = qualityCheckRepository.findTodayQualityChecks(startOfDay, endOfDay);
        statistics.put("todayChecks", todayChecks.size());
        
        // 需要返工的数量
        List<QualityCheck> reworkChecks = qualityCheckRepository.findByNeedsReworkTrue();
        statistics.put("reworkChecks", reworkChecks.size());
        
        // 平均质检分数（最近30天）
        LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
        Double averageScore = qualityCheckRepository.getAverageQualityScore(thirtyDaysAgo);
        statistics.put("averageScore", averageScore != null ? averageScore : 0.0);
        
        // 高质量订单数量
        List<QualityCheck> highQualityOrders = qualityCheckRepository.findHighQualityOrders();
        statistics.put("highQualityOrders", highQualityOrders.size());
        
        return ResponseEntity.ok(statistics);
    }

    @GetMapping("/report")
    @Operation(summary = "获取质检报表")
    public ResponseEntity<Map<String, Object>> getQualityCheckReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        
        Map<String, Object> report = new HashMap<>();
        
        // 这里可以根据日期范围生成详细报表
        LocalDateTime start = startDate != null ? LocalDateTime.parse(startDate) : LocalDateTime.now().minusDays(30);
        LocalDateTime end = endDate != null ? LocalDateTime.parse(endDate) : LocalDateTime.now();
        
        List<QualityCheck> checks = qualityCheckRepository.findByDateRange(start, end);
        
        report.put("totalChecks", checks.size());
        report.put("period", Map.of("start", start, "end", end));
        report.put("checks", checks);
        
        return ResponseEntity.ok(report);
    }
}
